#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, getopt
import re, codecs, os
from util import id_seq

def usage():
    print(" wrap id for markdown files.\n"+
""" Usage: %s [-v] [-x] [-e EXT] [-n --noid]<file>
            -v verbose
            -x use .n.md as a postfix
            -e use a new ext file as file.ext.md
            -n --noid to remove id in title
"""
            %sys.argv[0])

#TITLEREX='#+\s*(\d.)*'
TITLEREX = re.compile(r'#+\s*(\d+\.*)*\s+')
autoid = id_seq(1)

def convert_title(t, add=False):
    mret = TITLEREX.search(t)
    ret = t.rstrip()
    if mret:
        mstr = mret.group(0)
        mstrlen = len(mstr)
        count = mstr.rfind('#') + 1
        if count > 9:
            count = 9
        head = '#'*count
        if add:
            ret = head+' '+autoid.push(count)+' '+t[mstrlen:]
        else:
            ret = head+' '+t[mstrlen:]
    return ret

def convert(ifile, autoid=True, opost='.n.md', verbose=False):
    lines = []
    quotes = []
    with codecs.open(ifile, 'r', 'utf-8') as f:
        ofile = ifile + opost
        lines = f.readlines()
        maxl = len(lines)
        for i in range(maxl):
            l = lines[i]
            if l.startswith('```'):
                quotes.append(i)
            elif l.startswith('#'):
                if (len(quotes)%2) == 1:
                    continue
                newtitle = convert_title(l, autoid)
                if i < maxl and len(lines[i+1].split()):
                    lines[i] = newtitle+os.linesep
                else:
                    lines[i] = newtitle
                if (verbose):
                    print(lines[i].rstrip())
        if (verbose):
            for lno in quotes:
                print('Get quotes at ', lno)
    with codecs.open(ofile, 'w+', 'utf-8') as of:
        of.writelines(lines)

if __name__ == '__main__':
    autoid_flag = True
    postext = ''
    verbose_flag = False
    opts, args = getopt.getopt(
        sys.argv[1:],
        'e:hvnrx',
        [
            "help", "raw", "noid", "ext:"
            ]
        )

    if len(args) == 0 and len(opts) == 0:
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(2)
        elif o in ('-v'):
            verbose_flag = True
        elif o in ('-x'):
            postext = '.n.md'
        elif o in ('-e', '--ext'):
            postext = a
        elif o in ('-n', '--noid'):
            autoid_flag = False
        else:
            usage()
            sys.exit(2)

    for f in args:
        convert(f, autoid_flag, postext, verbose_flag)
